package ui;

import service.LibraryService;

import javax.swing.*;
import java.awt.*;

/**
 * 登录窗口，用于验证用户身份。
 */
public class LoginWindow extends JDialog {
    private final LibraryService service;
    private boolean loginSuccess = false;

    public LoginWindow(JFrame parent, LibraryService service) {
        super(parent, "用户登录", true);
        this.service = service;
        initializeUI();
    }

    /**
     * 初始化登录窗口界面。
     */
    private void initializeUI() {
        setLayout(new GridLayout(4, 2, 10, 10));
        setSize(350, 200);
        setLocationRelativeTo(null);

        JLabel userLabel = new JLabel("用户名:");
        JTextField userField = new JTextField();

        JLabel passLabel = new JLabel("密码:");
        JPasswordField passField = new JPasswordField();

        JButton loginButton = new JButton("登录");
        JButton cancelButton = new JButton("取消");

        // 登录按钮逻辑
        loginButton.addActionListener(e -> {
            String username = userField.getText();
            String password = new String(passField.getPassword());
            if (service.validateUser(username, password)) {
                loginSuccess = true;
                dispose(); // 关闭登录窗口
            } else {
                JOptionPane.showMessageDialog(this, "用户名或密码错误，请重试！", "登录失败", JOptionPane.ERROR_MESSAGE);
            }
        });

        // 取消按钮逻辑
        cancelButton.addActionListener(e -> {
            System.exit(0); // 关闭程序
        });

        add(userLabel);
        add(userField);
        add(passLabel);
        add(passField);
        add(new JLabel());
        add(loginButton);
        add(new JLabel());
        add(cancelButton);

        setVisible(true);
    }

    /**
     * 返回登录是否成功。
     * @return true 表示登录成功，false 表示登录失败或取消
     */
    public boolean isLoginSuccess() {
        return loginSuccess;
    }

}
